/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.icybear.gae.pechapaii;

import net.icybear.gae.pechapaii.service.TwitterService;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.icybear.gae.pechapaii.service.CryptoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import twitter4j.Twitter;
import twitter4j.TwitterException;

/**
 *
 * @author Bearice
 */
@Controller
@RequestMapping("/login.wml")
public class Login {

    @Autowired
    private TwitterService twitterService;
    @Autowired
    private CryptoService cryptoService;

    @RequestMapping
    public String login() {
        return "wml/login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String login(String user, String pass, Boolean save, HttpSession session, HttpServletRequest req, HttpServletResponse response) {
        try {
            user = URLDecoder.decode(user, "utf-8");
            pass = URLDecoder.decode(pass, "utf-8");
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException("decode failed", ex);
        }
        Twitter twitter = twitterService.twitterFactory.getInstance(user, pass);
        try {
            twitter.verifyCredentials();
        } catch (TwitterException ex) {
            req.setAttribute("message", "Login failed! (" + ex.getStatusCode() + ")");
            return "wml/login";
        } catch (Exception ex) {
            req.setAttribute("message", "Login failed! (" + ex.getMessage() + ")");
            return "wml/login";
        }
        session.setAttribute("user", user);
        session.setAttribute("pass", pass);
        if (save != null && save) {
            try {
                response.addCookie(new Cookie("user", cryptoService.encrypt(user)));
                response.addCookie(new Cookie("pass", cryptoService.encrypt(pass)));
            } catch (Exception ex) {
            }
        }
        return "redirect:timeline.wml";
    }
}
